package com.project.pet.controller.web;

import com.project.pet.common.ResponseData;
import com.project.pet.pojo.User;
import com.project.pet.pojo.UserDetailsImpl;
import com.project.pet.service.UserService;
import com.project.pet.utils.JwtTokenUtils;
import com.project.pet.utils.ResponseDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController("webUserController")
@RequestMapping("/api/web/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @PostMapping("/query")
    public ResponseData<Object> pagingQuery(@RequestBody HashMap<String,Object> map){
        return userService.pagingQuery(map);
    }

    @PostMapping("/login")
    public ResponseData<Object> login(@RequestBody User user) {
        Authentication authentication = null;
        try{
            //会自动调用loadUserByUsername方法，若查到用户，且用户名密码正确，则验证通过。
            // 关于密码的解密，配置在WebSecurityConfig类中（与注册时的加密策略保持相同）
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()));
        }catch (Exception e){
            e.printStackTrace();
            //当loadUserByUsername方法找不到用户时，会进入此异常
            //若查到用户，且用户名密码不匹配，会进入此异常
            return ResponseDataUtil.buildError("用户名不存在或密码错误");
        }
        //此处的UserDetailsImpl，就是loadUserByUsername方法返回的
        UserDetailsImpl userDetails = (UserDetailsImpl)authentication.getPrincipal();
        Map<String, Object> map = new HashMap<>();
        map.put("id",userDetails.getId());
        map.put("username",userDetails.getUsername());
        map.put("password",userDetails.getPassword());
        map.put("role",userDetails.getRole());
        String token = jwtTokenUtils.generateToken(userDetails.getId(), map);
        map.remove("password");
        map.put("token",token);
        map.put("userId",userDetails.getId());
        return ResponseDataUtil.buildSuccess(map);
    }
    @PostMapping("/register")
    public ResponseData<Object> register(@RequestBody User user){
        return userService.webRegister(user);
    }

    @PostMapping("/update")
    public ResponseData<Object> update(@RequestBody User user){
        return userService.webUpdate(user);
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @GetMapping("/test")
    public String test(){
        return "13";
    }

//    @PreAuthorize("hasAuthority('SELLER')")
    @GetMapping("/testLogin")
    public String testLogin(){
        return "ok";
    }

}
